package com.zhoux.ty.service.impl;

import com.zhoux.ty.dao.SysUserDao;
import com.zhoux.ty.domain.SysUser;
import com.zhoux.ty.service.SysUserService;
import com.zhoux.ty.web.util.EnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author: taoyi
 * @date: 2021/7/30 9:08
 * @version: 1.0
 * @explain:
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao userDao;

    /**
     * 用户登录
     * @param user
     * @return
     */
    @Override
    public String login(SysUser user) {
        SysUser user1 = new SysUser().setUsername(user.getUsername());
        SysUser user2 = userDao.selectOne(user1);
        if (user2==null)
            return null; // 没有查到数据
        System.out.println(user2);
        String sha256 = EnCode.getSHA256(user2.getSalt() + user.getPassword());
        if (!sha256.equals(user2.getPassword())){
            return null; // 密码错误
        }
        String token = UUID.randomUUID().toString().replace("-","");
        return token;
    }

    /**
     * 用户注册
     * @param user
     * @return
     */
    @Transactional
    @Override
    public int register(SysUser user) {
        int insert = 0;
        try {
            // 获取盐值
            String salt = EnCode.getSalt();
            user.setSalt(salt)
                    .setPassword(EnCode.getSHA256(salt+user.getPassword()))
                    .setValid("1");
            insert = userDao.insertUser(user);
        } catch (NoSuchAlgorithmException e) {
            System.out.println("盐值获取失败！！！");
            e.printStackTrace();
        }
        return insert;
    }
}
